using System;
using System.Collections;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.IO;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using Microsoft.ApplicationBlocks.ExceptionManagement;
using Dimok;
using ConfigWS = Dimok.Config.imaging.WS;
using ConfigPDF = Dimok.Config.imaging.PDF;
using Dimok.Data;
using Dimok.Data.Database;
using Dimok.Exceptions;
using Dimok.Images;
using Dimok.User;


namespace Dimok.Images{

	////////////////////////////////////////////////////////////////////////////////////////////////////
	/// <summary>	Exception for signalling no image folder identifier errors. </summary>
	///
	/// <remarks>	Dimon, 12/21/2010. </remarks>
	////////////////////////////////////////////////////////////////////////////////////////////////////

	public class NoImageFolderIDException : Exception{
		public NoImageFolderIDException():base("No ImageFolderID provided."){}
	}
	public class ShowApplImageFolder : System.Web.UI.Page{

		private string PDF_BUTTON_TEMPLATE = "/data/forms/buttontemplate.pdf";
		private string SUBMIT_BUTTON_NAME = "ButtonSubmit";
		
		#region Params ==============
		public static readonly string PARAM_FOLDER_ID = "FolderID";
		public static readonly string PARAM_PAGE_NUMBERS = "PageNums";

		////////////////////////////////////////////////////////////////////////////////////////////////////
		/// <summary>	Gets the image folder identifier parameter. </summary>
		///
		/// <value>	The image folder identifier parameter. </value>
		////////////////////////////////////////////////////////////////////////////////////////////////////

		public static string ImageFolderIDParam{

			////////////////////////////////////////////////////////////////////////////////////////////////////
			/// <summary>	Gets the get. </summary>
			///
			/// <value>	. </value>
			////////////////////////////////////////////////////////////////////////////////////////////////////

			get{
				return UserObject.GetQueryParam(PARAM_FOLDER_ID)+"";
			}
		}

		////////////////////////////////////////////////////////////////////////////////////////////////////
		/// <summary>	Gets the image folder i ds. </summary>
		///
		/// <value>	The image folder i ds. </value>
		////////////////////////////////////////////////////////////////////////////////////////////////////

		public static int[] ImageFolderIDs{
			get{
				return ImageFolderIDParam == "" ? new int[] { } : new StringList(ImageFolderIDParam);
			}
		}

		////////////////////////////////////////////////////////////////////////////////////////////////////
		/// <summary>	First page is 1. </summary>
		///
		/// <value>	The image page numbers parameter. </value>
		////////////////////////////////////////////////////////////////////////////////////////////////////

		public static StringList ImagePageNumbersParam{
			get{return new StringList(UserObject.GetQueryParam(PARAM_PAGE_NUMBERS).Split(new char[]{',','|'}));}
		}
		#endregion

		protected object _uox;

		////////////////////////////////////////////////////////////////////////////////////////////////////
		/// <summary>	Gets the uox v. </summary>
		///
		/// <value>	The uox v. </value>
		////////////////////////////////////////////////////////////////////////////////////////////////////

		protected virtual object _uox_v{get{return _uox == null ? _uox = new UserObject() : _uox;}}

		////////////////////////////////////////////////////////////////////////////////////////////////////
		/// <summary>	Gets the uox. </summary>
		///
		/// <value>	The uox. </value>
		////////////////////////////////////////////////////////////////////////////////////////////////////

		protected UserObject uox{get{ return (UserObject)_uox_v; }}

		////////////////////////////////////////////////////////////////////////////////////////////////////
		/// <summary>	Gets the page counts filter. </summary>
		///
		/// <value>	The page counts filter. </value>
		////////////////////////////////////////////////////////////////////////////////////////////////////

		protected virtual string PageCountsFilter{get{throw new Exception("This property must be implemented by derived class");}}

		////////////////////////////////////////////////////////////////////////////////////////////////////
		/// <summary>	Event handler. Called by Page for load events. </summary>
		///
		/// <remarks>	Dimon, 12/21/2010. </remarks>
		///
		/// <exception cref="ClientException">	Thrown when client. </exception>
		///
		/// <param name="sender">	Source of the event. </param>
		/// <param name="e">			Event information. </param>
		////////////////////////////////////////////////////////////////////////////////////////////////////

		private void Page_Load(object sender, System.EventArgs e){
			try{
				//ExceptionManager.Publish(new Exception("Image "+Request.QueryString+". Sent @ "+DateTime.Now.ToLongTimeString()));
				Context.Response.Cache.SetMaxAge(new TimeSpan(0,5,0));
				Context.Response.Expires = 1;
				byte[] image = null;
				#region Show Applicant's Folder
				if( uox.hasApplID ){
					if( ImageFolderIDs.Length != 1 ){
						int[] folderIDs = ImageFolderIDs;
						if( folderIDs.Length == 0 ){
							string sql = "SELECT ImageTypeID FROM PageCounts(@ApplID) WHERE [Count] > 0 "+PageCountsFilter+" ORDER BY TabIndex";
							folderIDs = SQLHelperEx.ExecuteScalarArray(uox.db_Images,sql,uox.applID);
						}
						image = Pages.ImageFolder(uox.db_Images, uox.applID, folderIDs, Enums.GetPageType(ConfigWS.DefaultContentTypeBulk));
					}else{
						string contentType = ConfigWS.DefaultContentType;
						//if( Regex.IsMatch(uox.UserName,RegistryBase.AppSettings("tiffUsers"),RegexOptions.IgnoreCase) )contentType = Enums.CONTENT_TYPES_PDF;
						image = Pages.ImageFolder(uox.db_Images,uox.applID,ImageFolderIDs[0],contentType,ImagePageNumbersParam);
					}
					if( image == null || image.Length == 0 ){
						string filter = ImageFolderIDParam == "" ? "1=1" : "ID IN ("+ImageFolderIDParam+")";
						string folderName = SQLHelperEx.ExecuteScalarArray(uox.db_Images,"SELECT ImageType FROM t_ImageType WHERE "+filter);
						Response.Write("<pre>No images in \""+folderName+"\" page(s) "+ImagePageNumbersParam+".</pre>");
						return;
					}
					if( false && Enums.GetPageType(image) == Dimok.Images.PageTypes.PDF /*&& ImagePageCountParam != 1*/ ){
						// Add Save button template
						try{
							//byte[] buttonTemplate = AcrobatClient.PrepButtonTemplate(FileManager.GetBytesFromFile(Server.MapPath(PDF_BUTTON_TEMPLATE),false),SUBMIT_BUTTON_NAME,ConfigPDF.PDFPostURL+"?"+Dimok.User.UserObject.APPL_ID_PARAM+"="+uox.applID+"&"+PARAM_FOLDER_ID+"="+ImageFolderIDParam+"&"+PARAM_PAGE_START+"="+ImagePageStartParam+"&"+PARAM_PAGE_COUNT+"="+ImagePageCountParam,256);
							//image = Dimok.Documents.PDF.CombinePDF(new byte[][]{image,buttonTemplate});
						}catch(Exception exc){ExceptionManager.Publish(exc);}
					}
				}
				#endregion
				#region Show File
				string fileName = UserObject.GetQueryParam("FileName");
				if( fileName != "" ){
					fileName = ImageFiles.FilePathFull(fileName);
					image =  ImageFiles.GetPages(fileName,ImagePageNumbersParam);
					if( image == null || image.Length == 0 ){
						Response.Write("<pre>File \""+fileName+"\" was not found.</pre>");
						return;
					}
				}
				#endregion
				if( image == null )
					throw new ClientException("Unknown request.");
				Response.ContentType = Enums.GetContentType(image);
				if (Response.ContentType == "application/octet-stream") {
					image = ABCPdf.TiffToPDF(image);
					Response.ContentType = Enums.GetContentType(image);
				}
				Response.Buffer = false;
				//Response.BinaryWrite( Dimok.Documents.PDF.LinearizePdf(image));
				Response.BinaryWrite(image);
			}catch(Exception exc){
				ASPException.Publish(exc);
				Response.ContentType = "text/html";
				Response.Write("<pre>"+ClientException.GetExceptions(exc)+"</pre>");
			}
		}

		#region Web Form Designer generated code

		////////////////////////////////////////////////////////////////////////////////////////////////////
		/// <summary>	Raises the initialise event. </summary>
		///
		/// <remarks>	Dimon, 12/21/2010. </remarks>
		///
		/// <param name="e">	Event information to send to registered event handlers. </param>
		////////////////////////////////////////////////////////////////////////////////////////////////////

		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}

		////////////////////////////////////////////////////////////////////////////////////////////////////
		/// <summary>	
		/// Required method for Designer support - do not modify the contents of this method with the code
		/// editor. 
		/// </summary>
		///
		/// <remarks>	Dimon, 12/21/2010. </remarks>
		////////////////////////////////////////////////////////////////////////////////////////////////////

		private void InitializeComponent()
		{    
			this.Load += new System.EventHandler(this.Page_Load);
		}
		#endregion
	}
}
